package cn.edu.zstu.qingzhu.qingzhushop.controller;


import cn.edu.zstu.qingzhu.qingzhushop.common.StatusCode;
import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import cn.edu.zstu.qingzhu.qingzhushop.provider.QiNiuProvider;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.storage.model.DefaultPutRet;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * FileName: QiniuController
 *
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020/7/29 21:27
 */
@RestController
@RequestMapping("/qiniu")
@Slf4j
@Api(tags = "七牛云对象存储功能接口")
public class QiNiuController {


    @Autowired
    private QiNiuProvider qiNiuProvider;

    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 七牛云文件上传
     *
     * @param file 文件
     * @return
     */
    @RequestMapping(value = "/upload",method = {RequestMethod.POST})
    //@ResponseBody
    public ResponseBean upload(MultipartFile[] file) {
        ResponseBean response = new ResponseBean(StatusCode.SC_INTERNAL_SERVER_ERROR);
        if (file.length <= 0 || file[0].isEmpty()) {
            return new ResponseBean(StatusCode.SC_EXPECTATION_FAILED,"上传文件不能为空");
        }
        try {
            String originalFilename = file[0].getOriginalFilename();
            String fileExtend = originalFilename.substring(originalFilename.lastIndexOf("."));
            String yyyyMMddHHmmss = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String fileKey = UUID.randomUUID().toString().replace("-", "") + "-" + yyyyMMddHHmmss + fileExtend;
            Map<String, Object> map = new HashMap<>();
            InputStream inputStream = file[0].getInputStream();
            DefaultPutRet uploadInfo = qiNiuProvider.upload(inputStream, fileKey);
            map.put("fileName", uploadInfo.key);
            map.put("originName", originalFilename);
            map.put("size", file[0].getSize());
            //七牛云文件私有下载地址（看自己七牛云公开还是私有配置）
            map.put("url", qiNiuProvider.getPrivateFile(uploadInfo.key));
//           map.put("url", "/linfen/qiniu/file/" + uploadInfo.key);//七牛云公开下载地址
            //String json = objectMapper.writeValueAsString(map);
            response.setStatus(0);
            response.setMsg("成功");
            response.setData(map);
            log.info("文件：" + map);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return response;
        }
    }

    /**
     * 七牛云私有文件下载
     *
     * @param filename 文件名
     * @return
     */
    @RequestMapping(value = "/private/file/{filename}",method = {RequestMethod.GET})
    public void privateDownload(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (filename.isEmpty()) {
            return;
        }

        try {
            String privateFile = qiNiuProvider.getPrivateFile(filename);
            log.info("文件下载地址：" + privateFile);
            response.sendRedirect(privateFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 七牛云文件下载
     *
     * @param filename 文件名
     * @return
     */
    @RequestMapping(value = "/file/{filename}",method = {RequestMethod.GET})
    public void download(@PathVariable("filename") String filename, HttpServletResponse response) {
        if (filename.isEmpty()) {
            return;
        }

        try {
            String publicFile = qiNiuProvider.getFile(filename);
            System.out.println("文件下载地址：" + publicFile);
            response.sendRedirect("http://"+publicFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
